/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package koor.action.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import koor.action.Action;
import koor.action.ActionResult;
import koor.authorization.UserAuthorisation;
import koor.persistent.UserDAO;
import koor.service.ServiceLocator;

/**
 * The
 * <code>UserDeleteAction</code> class represents admin action, used to remove
 * user
 *
 * @author Admin
 */
public class UserDeleteAction implements Action {

    @Override
    public String getName() {
        return "user.delete";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        if (request.getParameter("id") != null) {
            try {
                Long id = Long.parseLong(request.getParameter("id"));
                UserDAO userDao = ServiceLocator.getService(UserDAO.class);
                String userLogin = request.getParameter("login");
                String currentAdminLogin = ((UserAuthorisation) request.getSession().getAttribute("userAuth")).getUser().getLogin();
                if (!userLogin.equalsIgnoreCase(currentAdminLogin)) {
                    userDao.deleteById(id);
                    request.getSession().setAttribute("win", "Пользователь удален");
                } else {
                    request.getSession().setAttribute("fail", "Нельзя удалить текущего пользовател");
                }
            } catch (NumberFormatException e) {
                request.getSession().setAttribute("fail", "Некорректиный номер пользователя");
            } catch (RuntimeException e) {
                request.getSession().setAttribute("fail", "Пользователь не найден");
            }
        } else {
            request.getSession().setAttribute("fail", "Не удалось удалить пользователя");
        }
        return ActionResult.redirect("employee");
    }
}
